import { _decorator, AudioClip, Component, Node, sp } from 'cc';
import { AudioMgr } from './AudioMgr';
const { ccclass, property } = _decorator;
const ColorAniList = ['bule', 'red', 'white', 'yellow']
@ccclass('LighAnimation')
export class LighAnimation extends Component {
    @property({ type: [Node] })
    public lightNodes: Node[] = []; // 灯光节点数组，用于存储所有灯光节点
    @property({ type: [Node] })
    public ribbonNodes: Node[] = []; // 彩虹节点数组，用于存储所有彩虹节点
    @property({ type: Number })
    public stopDelay: number = 0.1; // 动画停止延迟时间(秒)
    @property({ type: Number })
    public errorTime: number = 3; // 动画停止误差时间(秒)
    // 可配置参数
    @property({ type: Number })
    public duration: number = 8; // 动画总时长(秒)
    @property(AudioClip)
    public lightAnimateSound: AudioClip;
    @property(AudioClip)
    public heroSelected: AudioClip;

    // 动画控制相关属性
    private currentIndex: number = 0; // 当前激活的灯光节点索引
    private elapsedTime: number = 0; // 动画已运行的总时间(秒)
    private switchTimer: number = 0; // 灯光切换计时器
    private currentSwitchInterval: number = 0.1; // 当前灯光切换间隔时间(秒)
    private isRunning: boolean = false; // 动画是否正在运行

    private ribbonTargetIndex: number = 0; // 彩虹最终显示位置索引
    private animationState: 'fast' | 'slow' | 'pause' | 'show_ribbon' = 'fast';
    private fastDuration: number = 0; // 快速运行时长
    private slowDuration: number = 0; // 减速时长
    private callBack: Function;
    private thisArg: any;
    private _excludeIndex: number = -1;
    start() {
        this.init();
    }

    private init() {
        this.lightNodes.forEach((node, index) => {
            node.active = false;
        });
        this.ribbonNodes.forEach((node, index) => {
            node.active = false;
        });
    }
    setColor(colorList: number[]) {
        this.lightNodes.forEach((node, index) => {
            node.children[0].getComponent(sp.Skeleton).setAnimation(0, ColorAniList[colorList[index]]);
        });
    }
    setActive(index: number, active: boolean) {
        // 如果索引是被排除的索引，则不允许激活
        if (index === this._excludeIndex) {
            this.lightNodes[index].active = false;
        } else {
            this.lightNodes[index].active = active;
        }
    }
    public showLight(index: number) {
        // 如果索引是被排除的索引，则不显示
        if (index !== this._excludeIndex) {
            this.lightNodes[index].active = true;
        }
    }
    public startAnimation(targetIndex: number, excludeIndex: number = -1, fb?: Function, thisObj?: any) {
        if (targetIndex === excludeIndex) {
            throw ('目标索引不能与排除索引相同');
        }
        this._excludeIndex = excludeIndex;
        this.callBack = fb;
        this.thisArg = thisObj;
        this.init();

        this.ribbonTargetIndex = targetIndex; // 确保ribbonTargetIndex被正确初始化
        this.currentIndex = 0;
        // 如果初始索引是排除的索引，则跳到下一个
        if (this.currentIndex === this._excludeIndex) {
            this.currentIndex = (this.currentIndex + 1) % this.lightNodes.length;
        }

        // console.log(`开始动画 - 目标索引: ${targetIndex}, 排除索引: ${excludeIndex}, 初始索引: ${this.currentIndex}`);

        // 计算时间分配：快速70%，减速30%
        this.fastDuration = this.duration * 0.7;
        this.slowDuration = this.duration * 0.3;

        this.isRunning = true;
        this.elapsedTime = 0;
        this.switchTimer = 0;
        this.currentSwitchInterval = 0.1;
        this.animationState = 'fast';
    }

    update(deltaTime: number) {
        if (!this.isRunning) return;

        this.elapsedTime += deltaTime;
        this.switchTimer += deltaTime;

        // 状态切换逻辑
        if (this.animationState === 'fast' && this.elapsedTime >= this.fastDuration) {
            this.animationState = 'slow';
        }

        // 根据状态设置不同的切换间隔
        if (this.animationState === 'fast') {
            this.currentSwitchInterval = 0.1; // 快速切换
        } else {
            // 减速效果
            const progress = (this.elapsedTime - this.fastDuration) / this.slowDuration;
            this.currentSwitchInterval = 0.1 + (1.0 * progress * progress);
        }

        // 切换灯光节点
        if (this.switchTimer >= this.currentSwitchInterval) {
            this.switchTimer = 0;
            // 跳过排除的索引
            do {
                this.currentIndex = (this.currentIndex + 1) % this.lightNodes.length;
            } while (this.currentIndex === this._excludeIndex);
            this.updateLightNodes();
        }

        // 停止逻辑
        if (this.elapsedTime >= this.fastDuration + this.slowDuration) {
            this.isRunning = false;
            // 确保最终停止在目标索引上
            this.currentIndex = this.ribbonTargetIndex;
            this.animationState = 'pause';
            this.updateLightNodes();

            setTimeout(() => {
                this.animationState = 'show_ribbon';
                this.updateLightNodes();
                this.callBack?.call(this.thisArg);
            }, 100);
        }
    }

    private updateLightNodes() {
        if (this.animationState !== 'show_ribbon') {
            this.lightNodes.forEach((node, index) => {
                // 排除索引永远不激活，其他索引根据currentIndex决定
                node.active = (index !== this._excludeIndex) && (index === this.currentIndex);
            });
            AudioMgr.inst.playOneShot(this.lightAnimateSound);
        } else {
            this.lightNodes.forEach(node => node.active = false);
        }

        this.ribbonNodes.forEach((node, index) => {
            node.active = this.animationState === 'show_ribbon' && index === this.ribbonTargetIndex;
            if (node.active) {
                node.children[0].getComponent(sp.Skeleton).setAnimation(0, 'idle', false);
                AudioMgr.inst.playOneShot(this.heroSelected);
            }
        });
    }

    public playResult(targetIdx: number) {

        this.lightNodes.forEach(node => node.active = false);
        this.ribbonNodes.forEach((node, index) => {
            node.active = index === targetIdx;
            if (node.active) {
                AudioMgr.inst.playOneShot(this.heroSelected);
                node.children[0].getComponent(sp.Skeleton).setAnimation(0, 'idle', false);
            }
        });
    }
}



